package com.monkeyboy.mongo_demo;

import com.mongodb.client.MongoCollection;
import com.monkeyboy.util.MongoDBAuthUtil;
import org.bson.Document;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 插入文档
 * @Author Gavin
 * @date 2021.01.10 17:39
 */
public class InsertMongodbDemo {
    public static void main(String[] args) {
        InsertMongodbDemo insertMongodbDemo = new InsertMongodbDemo();
        insertMongodbDemo.insertManyDocument();
    }

    //添加多个文档
    public void insertManyDocument() {
        MongoCollection<Document> collection = MongoDBAuthUtil.getCollection("test", "java_coll");
        List<Document> list = new ArrayList<Document>();
        //创建Document对象
        Document doc = new Document();
        doc.append("username", "Liada").append("age", 18).append("tags", Arrays.asList("go", "javascript"));
        //创建Document对象
        Document doc2 = new Document();
        doc2.append("username", "llq").append("age", 46).append("tags", Arrays.asList("php", "html"));
        list.add(doc);
        list.add(doc2);
        collection.insertMany(list);
    }

    //添加单个文档
    public void insertSingleDocument() {
        MongoCollection<Document> collection = MongoDBAuthUtil.getCollection("test", "java_coll");
        //创建Document对象
        Document doc = new Document();
        doc.append("username", "Gavin").append("age", 26).append("tags", Arrays.asList("java", "python"));
        collection.insertOne(doc);
    }
}
